package com.yjsn.base.filter;

import com.yjsn.base.config.RequestWrapper;
import com.yjsn.base.utils.StringUtils;
import com.yjsn.base.utils.uuid.IdUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.core.NamedThreadLocal;

import java.io.IOException;

/**
 * @author taopenghui
 * @date 2022-03-31 17:05:54
 **/
@WebFilter(urlPatterns = "/*")
public class MdcFilter implements Filter {

	private static final String TRACE_ID = "trace_id";

	private static final Logger log = LoggerFactory.getLogger(MdcFilter.class);

	/** traceId */
	private static final ThreadLocal<String> traceId = new NamedThreadLocal<String>("Trace ID");

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		try {
			HttpServletRequest httpServletRequest = (HttpServletRequest) request;
			String sign = httpServletRequest.getHeader("x-b3-traceid");
			if(StringUtils.isBlank(sign)) sign = IdUtils.fastSimpleUUID();
			MDC.put(TRACE_ID, sign);
			traceId.set(sign);
			log.info("request url:{}", ((HttpServletRequest) request).getRequestURI());
			if (httpServletRequest instanceof HttpServletRequest) {
				HttpServletRequest httpRequest = (HttpServletRequest) request;
				RequestWrapper requestWrapper = new RequestWrapper(httpRequest);
				chain.doFilter(requestWrapper, response);
			} else {
				chain.doFilter(request, response);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		} finally {
			MDC.remove(TRACE_ID);
			traceId.remove();
		}
	}

	@Override
	public void destroy() {

	}

}
